﻿var grid_selector = "#grid-table";
var pager_selector = "#grid-pager";
var pattern = new RegExp(/<script.*?>.*?<\/script>/ig);
$(function ($) {
    var parent_column = $(grid_selector).closest('[class*="col-"]');
    $(window).on('resize.jqGrid', function () {
        $(grid_selector).jqGrid('setGridWidth', parent_column.width());
    });
    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
        if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
            setTimeout(function () {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            }, 20);
        }
    });
    if (!pEdit) {
        //EditOpt
        $(colModel).each(function (i, v) {
            if (v.id == "EditOpt") {
                colModel.splice(i, 1);
            }
        });
    }
    $(grid_selector).jqGrid({
        caption: caption,
        url: dataUrl,
        mtype: "POST",
        datatype: "local",
        height: 320,
        colModel: colModel,
        viewrecords: true,
        rowNum: 20,
        rowList: [20, 30, 50],
        pager: pager_selector,
        altRows: true,
        multiselect: multiselect,
        multiboxonly: true,
        loadComplete: function(data) {
            try {
                if (!data.success) {
                    TipMsg(data.message);
                }
            } catch (e) {
                var table = this;
                setTimeout(function() {
                    updatePagerIcons(table);
                }, 0);
            }
        }
    });
    $(window).triggerHandler('resize.jqGrid');

    function updatePagerIcons(table) {
        var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        });
    }
    Search();
    $("#btnSearch").click(function () {
        Search();
    });
});
function Search() {
    var postData = $(grid_selector).jqGrid("getGridParam", "postData");
    var sidx = "";
    var sord = "";
    $.each(postData, function (k, v) {
        if (k == "sidx") {
            sidx = v;
        }
        else if (k == "sord") {
            sord = v;
        }
    });
    var formparms = $("#SearchForm").formToArray();
    var parm = "page=1&rows=" +
        jQuery(grid_selector).jqGrid('getGridParam', 'rowNum') +
        "&sidx=" + sidx +
        "&sord=" + sord;
    var parmdata = new Array();
    $.each(parm.split('&'), function (k, v) {
        parmdata.push("\"" + v.split('=')[0] + "\":\"" + v.split('=')[1] + "\"");
    });
    $.each(formparms, function (k, v) {
        parmdata.push("\"" + v.name + "\":\"" + v.value + "\"");
    });
    $(grid_selector).jqGrid("setGridParam", { page: 1, datatype: "json", postData: JSON.parse("{" + parmdata.join(",") + "}") }).trigger("reloadGrid");
}
function windowsLoad() {
    $("#my-modal-info", window.parent.document).modal("hide");
    $(grid_selector).trigger("reloadGrid");
}

function AddItem(url) {
    $.ajax({
        url: url,
        data: $("#SearchForm").formSerialize(),
        type: "get",
        success: function (data) {
            try {
                if (!data.success) {
                    TipMsg(data.message);
                }
            } catch (err) {
                $("#my-modal-info .modal-footer", window.parent.document).show();
                $("#my-modal-info #saveBtn", window.parent.document).off("click");
                loadfun(data, $("#my-modal-info .modal-body", window.parent.document));
                $("#my-modal-info", window.parent.document).modal({ backdrop: 'static', keyboard: false });
            }
        },
        error: function (e) {
            TipMsg("出错了,请稍后再试!");
        }
    });
}

function EditItem(url, id) {
    $.ajax({
        url: url + "?Id=" + id,
        type: "get",
        success: function (data) {
            try {
                if (!data.success) {
                    TipMsg(data.message);
                }
            } catch (err) {
                $("#my-modal-info .modal-footer", window.parent.document).show();
                $("#my-modal-info #saveBtn", window.parent.document).off("click");
                loadfun(data, $("#my-modal-info .modal-body", window.parent.document));
                $("#my-modal-info", window.parent.document).modal({ backdrop: 'static', keyboard: false });
            }
        },
        error: function (e) {
            TipMsg("出错了,请稍后再试!");
        }
    });
}
function DelItem(url) {
    var ids = $(grid_selector).jqGrid("getGridParam", "selarrrow");
    if (ids.length == 0) {
        TipMsg("请选择至少一条要删除的记录!");
        return;
    }
    TipConfirm("确认删除吗?", ConfirmDel, url);
}
function ConfirmDel(url) {
    var ids = $(grid_selector).jqGrid("getGridParam", "selarrrow");
    var rowId = new Array();
    ids.forEach(function (e) {
        var rowData = $(grid_selector).jqGrid('getRowData', e);
        rowId.push(rowData.id);
    });
    $.ajax({
        url: url,
        data: { ids: rowId.join(',') },
        type: "post",
        dataType: "json",
        success: function (data) {
            if (data.success) {
                TipMsg(data.message, $(window.parent.document).contents().find("#mainFrame")[0].contentWindow.windowsLoad);
            } else {
                TipMsg(data.message);
            }
        },
        error: function (e) {
            TipMsg("出错了,请稍后再试!");
        }
    });
}

function ExportItem(url) {
    if (TipConfirm("确定要按照当前选择的条件导出数据吗?", function() {
        
        var postData = $(grid_selector).jqGrid("getGridParam", "postData");
        var sidx = "";
        var sord = "";
        $.each(postData, function(k, v) {
            if (k == "sidx") {
                sidx = v;
            } else if (k == "sord") {
                sord = v;
            }
        });
        var formparms = $("#SearchForm").formToArray();
        var parm = "page=0&rows=0" +
            "&export=true" +
            "&sidx=" + sidx +
            "&sord=" + sord;
        $.each(formparms, function(k, v) {
            parm += ("&" + v.name + "=" + v.value + "");
        });
        $.ajax({
            url: url,
            data: parm,
            type: "get",
            success: function(data) {
                $("#my-modal-info .modal-footer", window.parent.document).show();
                $("#my-modal-info #saveBtn", window.parent.document).off("click");
                loadfun(data, $("#my-modal-info .modal-body", window.parent.document));
                $("#my-modal-info", window.parent.document).modal({ backdrop: 'static', keyboard: false });
            },
            error: function(e) {
                TipMsg("出错了,请稍后再试!");
            }
        });
    }));
}

function ViewItem(url) {
    var id = $(grid_selector).jqGrid("getGridParam", "selrow");
    if (id == null) {
        TipMsg("请选择要查看的记录!");
        return;
    }
    $.ajax({
        url: url + "?Id=" + $(grid_selector).jqGrid('getRowData', id).ID,
        type: "post",
        success: function (data) {
            try {
                if (!data.success) {
                    TipMsg(data.message);
                }
            } catch (err) {
                $("#my-modal-info .modal-footer", window.parent.document).hide();
                loadfun(data, $("#my-modal-info .modal-body", window.parent.document));
                $("#my-modal-info", window.parent.document).modal("show");
            }
        },
        error: function (e) {
            TipMsg("出错了,请稍后再试!");
        }
    });
}
function editIcon(cellvalue, options, rowObject) {
    return "<a href='javascript:;' onclick=\"EditItem('" + pEditUrl + "','" + rowObject.id + "')\"><i class=\"fa fa-pencil blue\"></i></a>";
}
//将js文件输出到父框架内
function loadfun(data, modal) {
    var matchArr = data.match(pattern);
    var topFunsrc = [];
    $(matchArr).each(function (i, v) {
        if (v.length > 0) {
            if ($(v).prop("src").length > 0) {
                topFunsrc.push($(v).prop("src"));
                data = data.replace(v, "");
            }
        }
    });
    modal.html(data);
    $("#childFun", window.parent.document).html("");
    $(topFunsrc).each(function (i, v) {
        parent.loadfun(v);
    });
}